package com.xiaomage.handlerdemo

import android.os.*
import java.util.*

class DownHandlerThread(name: String?) : HandlerThread(name), Handler.Callback {
    //定义读取关键字
    private val KEY_URL="url"
    private var workHandler:Handler?=null
    private var uiHandler:Handler?=null
    private val urlList=ArrayList<String>()
    fun setUIHandlere(uiHandler:Handler?){
        this.uiHandler=uiHandler
    }

    fun setDownUrl(vararg urls:String){
        for(url in urls){
            urlList.add(url)
        }
    }

    override fun onLooperPrepared() {
        super.onLooperPrepared()
        //执行初始化任务
        workHandler=Handler(looper,this)
        for(url in urlList){
            val message=workHandler?.obtainMessage()
            val bundle=Bundle()
            bundle.putString(KEY_URL,url)
            message?.data=bundle
            workHandler?.sendMessage(message)
        }


    }
    override fun handleMessage(msg: Message?): Boolean {
        if(msg==null || msg.data==null){
            return false
        }
        val url=msg.data.getString(KEY_URL)
        val startMessage=uiHandler?.obtainMessage(0x110,"开始下载：$url---当前时间${System.currentTimeMillis()}")
        uiHandler?.sendMessage(startMessage)

        SystemClock.sleep(2000)

        val endMessage=uiHandler?.obtainMessage(0x120,"下载完成：$url---当前时间${System.currentTimeMillis()}")
        uiHandler?.sendMessage(endMessage)


        return true
    }

    override fun quitSafely(): Boolean {
        uiHandler=null
        return super.quitSafely()
    }
}